package craky.keeper.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOUtil
{
    private static final int BUFFER_SIZE = 1024 * 1024;

    public static void in2OutStream(InputStream in, OutputStream out, int bufferSize) throws IOException
    {
        byte[] buffer = new byte[bufferSize];

        for(int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;)
        {
            out.write(buffer, 0, bytesRead);
        }
    }

    public static void copyFile(File src, File dest, boolean cover) throws IOException
    {
        copyFile(new FileInputStream(src), dest, cover);
    }

    public static void copyFile(InputStream in, File dest, boolean cover) throws IOException
    {
        FileOutputStream out = null;

        try
        {
            if(!dest.exists())
            {
                dest.createNewFile();
            }
            else if(dest.exists() && cover)
            {
                dest.delete();
                dest.createNewFile();
            }
            else
            {
                throw new IOException("File " + dest + " already exists");
            }

            out = new FileOutputStream(dest);
            in2OutStream(in, out, BUFFER_SIZE);
        }
        finally
        {
            try
            {
                if(in != null)
                {
                    in.close();
                }
            }
            finally
            {
                if(out != null)
                {
                    out.close();
                }
            }
        }
    }

    public static void mkdirs(File dir)
    {
        if(!dir.exists())
        {
            File parent = dir.getParentFile();

            if(!parent.exists())
            {
                mkdirs(parent);
            }

            dir.mkdir();
        }
    }
}